import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanxiang_app/bean/config_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/bean/version_entity.dart';
import 'package:wanxiang_app/pages/login/login.dart';
import 'package:wanxiang_app/pages/my/my.dart';
import 'package:wanxiang_app/pages/sell/sell2.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/tabChangeEvent.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import 'package:wanxiang_app/widgets/sell_tip_dialog.dart';

import '../bean/agreement_entity.dart';
import '../bean/msg_log_entity.dart';
import '../utils/constant.dart';
import '../utils/network_manager.dart';
import '../utils/network_url.dart';
import '../utils/toast_util.dart';
import '../widgets/agreement_dialog.dart';
import '../widgets/privacy_dialog.dart';
import '../widgets/simple_dialog.dart';
import '../widgets/tip_dialog.dart';
import 'buy/buy.dart';
import 'home/home.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:io';
import 'home/hot.dart';
import 'login/login_code.dart';
import 'msg/msg.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_update_dialog/flutter_update_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:event_bus/event_bus.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:badges/badges.dart' as badges;
import 'package:ota_update/ota_update.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:crypto/crypto.dart';
import 'package:permission_handler/permission_handler.dart';

class IndexController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    _doInitializeSDK();
    _getVersion();
    _getService();



    Future.delayed(Duration(milliseconds: 500),(){
      // showNoticeDialog();
      // _timerGet();
    });
    Future.delayed(Duration(seconds: 3),(){
      // _timerGet();
    });
    tabbarEventBus.on<TabChangedEvent>().listen((event) {
      if (event.tabIndex == -1) {
        page = 0;
        pageController.animateToPage(page,
            duration: Duration(milliseconds: 50), curve: Curves.fastOutSlowIn);
        update();
      } else if (event.tabIndex == 100) {
        _getUnReadTotal();
      } else if (event.tabIndex == 200) {
        unReadNum = 0;
      } else if (event.tabIndex == 400) {
        page = 3;
        pageController.animateToPage(page,
            duration: Duration(milliseconds: 50), curve: Curves.fastOutSlowIn);
        update();
      } else if (event.tabIndex == 500) {
        page = 2;
        pageController.animateToPage(page,
            duration: Duration(milliseconds: 50), curve: Curves.fastOutSlowIn);
        update();
      } else if (event.tabIndex == 1000) {
        pageController.animateToPage(page,
            duration: Duration(milliseconds: 50), curve: Curves.fastOutSlowIn);
        update();
      }else if(event.tabIndex == 2000){
        _getUnReadTotal();
      }
      else{

      }
    });

    EasyRefresh.defaultHeaderBuilder = () => ClassicHeader();
    EasyRefresh.defaultFooterBuilder = () => ClassicFooter();
  }


  _nimLogin() async {
    String md5Str = md5
        .convert(utf8.encode(UserUtil.getUSER()!.userName))
        .toString()
        .toUpperCase();
    final loginResult = await NimCore.instance.authService.login(NIMLoginInfo(
      account: UserUtil.getUSER()!.userName,
      token: md5
          .convert(utf8.encode(UserUtil.getUSER()!.userName))
          .toString()
          .toUpperCase(),
      //authType: NIMAuthType.authTypeDynamic,
    ));
    if (loginResult.isSuccess) {
      _getUnReadTotal();
    }
    // Get.back();
  }

  void _listenMsg() {
    NimCore.instance.messageService.onMessage.listen((messages) {
      _sendWriteMsg("监听到消息进入");
      _getUnReadTotal();
      tabbarEventBus.fire(TabChangedEvent(3));
    });
  }
  void _sendWriteMsg(msg) {
    // 创建一个 MethodChannel 对象，通道名称为 "app.channel.notifaction"
    const platform = MethodChannel('app.channel.notifaction');
// 调用原生平台方法
    try {
      var sharedData = platform.invokeMethod('writemsg',{
        "msg":msg,
      });
      // 处理原生平台返回值
    } on PlatformException catch (e) {
      // 处理调用原生平台方法时出现的错误
    }
  }

  void _sendChannel() {
    // 创建一个 MethodChannel 对象，通道名称为 "app.channel.notifaction"
    const platform = MethodChannel('app.channel.notifaction');
// 调用原生平台方法
    try {
      var sharedData = platform.invokeMethod('notifactionJson');
      // 处理原生平台返回值
    } on PlatformException catch (e) {
      // 处理调用原生平台方法时出现的错误
    }
  }

  void _getService() {
    if (UserUtil.getFirst().isNotEmpty) {
      _sendChannel();
      return;
    }
    DioManager.getInstance().post(ServiceUrl.privacy, null, (data) async {
      AgreementEntity bannerEntity = AgreementEntity.fromJson(jsonDecode(data));
      showDialog(
          context: mContext,
          builder: (BuildContext context1) {
            return MyAPrivacyDialog(
              callBack: (String content) {
                if (content == 'cancel') {
                  Navigator.pop(context1);
                } else if (content == 'sure') {
                  _sendChannel();
                  UserUtil.saveFirst('init');
                  Navigator.pop(context1);
                }
              },
              sureText: "已阅读并同意",
              msg: bannerEntity.data.content,
            );
          });
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _doInitializeSDK() async {
    late NIMSDKOptions options;
    var config = NIMStatusBarNotificationConfig(
      ring: true,
        vibrate:true,
        showBadge:true
    );
    if (Platform.isAndroid) {
      final directory = await getExternalStorageDirectory();
      final xmPushConfig = NIMMixPushConfig(
        xmAppId: '2882303761520278656',
        xmAppKey: '5882027815656',
        xmCertificateName: '淘号阁小米推送证书',

        hwAppId: '109583685',
        hwCertificateName:'淘号阁华为推送证书',

        mzAppId:'153878',
        mzAppKey:'293c33889a7b49b7b956398e21b00b06',
        mzCertificateName:'淘号阁魅族推送证书',

        vivoCertificateName:'淘号阁VIVO推送证书',

        oppoAppId:'31421197',
        oppoAppKey:'e6ffbbba1e0e4c7ea6e4592e756a4760',
        oppoAppSecret:'8b22aea597c7491c9729648a3acce763',
        oppoCertificateName:'淘号阁oPPO推送证书',

        honorCertificateName:'淘号阁荣耀推送证书',
        autoSelectPushType: true

      );
      NimCore.instance.settingsService.enableNotificationAndroid(enableRegularNotification: true,
          enableRevokeMessageNotification: true);
      options = NIMAndroidSDKOptions(
          appKey: Constant.appKey,
          notificationConfig: config,
          shouldSyncStickTopSessionInfos: true,
          mixPushConfig: xmPushConfig,
          sdkRootDir:
              directory != null ? '${directory.path}/NIMFlutter' : null);


    } else if (Platform.isIOS) {
      final directory = await getApplicationDocumentsDirectory();
      options = NIMIOSSDKOptions(
        appKey: Constant.appKey,
        shouldSyncStickTopSessionInfos: true,
        sdkRootDir: '${directory.path}/NIMFlutter',
        apnsCername: 'ENTERPRISE',
        pkCername: 'DEMO_PUSH_KIT',
      );
    }
    NimCore.instance.initialize(options).then((value) async {
      NimCore.instance.messageService.setChattingAccount(
        sessionId: 'none',
        sessionType: NIMSessionType.p2p,
      );
      NimCore.instance.messageService.setChattingAccount(
        sessionId: 'none',
        sessionType: NIMSessionType.team,
      );
      if (UserUtil.getUSER() != null) {
        NimCore.instance.settingsService.updateNotificationConfigAndroid(config);
        _nimLogin();

        _listenMsg();
      }
    });
  }

  int unReadNum = 0;

  _timerGet(){
    // var time = Timer.periodic(Duration(milliseconds: 3000), (t) {
    //   if(UserUtil.getUSER()!=null && UserUtil.getUSER()!.nickname.isNotEmpty){
    //     _getUnReadTotal();
    //   }
    //
    // });
  }

  void _getUnReadTotal() async {
    NIMResult<int> result =
        await NimCore.instance.messageService.queryTotalUnreadCount();
    unReadNum=0;
    DioManager.getInstance().post(ServiceUrl.getMessageLog, {
      "user_id": UserUtil.getUSER()?.id.toString(),
      "page": '1',
      "pagesize": "500"
    }, (data) async {
      unReadNum=0;
      MsgLogEntity bannerEntity = MsgLogEntity.fromJson(jsonDecode(data));
      for (int i = 0; i < bannerEntity.data.length; i++) {
        if(bannerEntity.data[i].isRead!=1){
          unReadNum ++;
        }
      }
      unReadNum =unReadNum+ result.data!;
      _sendWriteMsg("当前APP是否前台==$isFront");
      if( !isFront){
        _sendWriteMsg("当前未读数量==$unReadNum");
        _sendUnreadChannel();
      }

      update();
    }, (error) {

      ToastUtil.show(error);
    });
  }
  Future<Null> _sendUnreadChannel() async {
    print('sharedDataeeee=_sendUnreadChannel_sendUnreadChannel');
    // 创建一个 MethodChannel 对象，通道名称为 "app.channel.notifaction"
    const platform = MethodChannel('app.channel.notifaction');
// 调用原生平台方法
    try {
      var sharedData = platform.invokeMethod('getbadge',{
        "badgenum": unReadNum.toString(),
      });
      // 处理原生平台返回值
    } on PlatformException catch (e) {
      // 处理调用原生平台方法时出现的错误
    }
  }
  late BuildContext mContext;

  String buildNumber = '';
  String version = '';

  void _getVersion() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      version = packageInfo.version;
      buildNumber = packageInfo.buildNumber;
      _getVersion1();
    });
  }

  late VersionData versionData;

  void _getVersion1() {
    String version_type = '';
    if (Platform.isIOS) {
      version_type = 'ios';
    } else {
      version_type = '安卓';
    }
    DioManager.getInstance().postJson(
        ServiceUrl.checkVersion, {'version_type': version_type}, (data) {
      VersionEntity bannerEntity = VersionEntity.fromJson(jsonDecode(data));
      versionData = bannerEntity.data;
      if (bannerEntity.code == 200) {
        if (version != bannerEntity.data.versioncode) {
          Timer(const Duration(milliseconds: 500), () => defaultStyle());
        }
      } else {}
    }, (error) {
      ToastUtil.show(error);
    });
  }

  PageController pageController = new PageController();
  int page = 0;
  UpdateDialog? dialog;
  String versionUrl = '';

  double progress = -1.1.obs;
  StreamSubscription<OtaEvent>? otaEvent;

  void defaultStyle() {
    // if (dialog != null && dialog.isShowing()) {
    //   return;
    // }

    dialog = UpdateDialog.showUpdate(mContext,
        title: "有新版本了",
        updateContent: versionData.versionCount,
        progress: progress, onIgnore: () {
      if (otaEvent != null) {
        otaEvent!.cancel();
      }
      dialog!.dismiss();
    }, enableIgnore: false,isForce: true, onUpdate: onUpdate);

    // dialog?.show();
  }

  void onUpdate() {
    // dialog?.dismiss();
    print('开始升级');
    // if (Platform.isIOS) {
    //   launch('https://apps.apple.com/us/app/id1567019854',
    //       forceSafariVC: false);
    // } else {
    //浏览器下载
    // launch(versionData.versionUrl, forceSafariVC: false);
    // }

    if (Platform.isIOS) {
      launch(versionData.versionUrl, forceSafariVC: false);
    } else {
      try {
        otaEvent = OtaUpdate()
            .execute(
          versionData.versionUrl,
          // OPTIONAL
          destinationFilename: 'tbg.apk',
          //OPTIONAL, ANDROID ONLY - ABILITY TO VALIDATE CHECKSUM OF FILE:
        )
            .listen(
          (OtaEvent event) {
            // BotToast.showLoading();
            if (dialog!.isShowing()) {
              progress = double.parse(event.value!) / 100;
              dialog?.update(progress);
            } else {
              otaEvent?.pause();
              otaEvent?.cancel();
            }
          },
        );
      } catch (e) {
        print('Failed to make OTA update. Details: $e');
      }
    }
  }

  bool tabFirst = true;
  int preIndex = 0;
  bool isFront = false;
}

class IndexPage extends GetView<IndexController>  with WidgetsBindingObserver{
  late IndexController controller;

  late BuildContext context;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<IndexController>(() => IndexController());
    controller = Get.find();
    context = context1;
    showNoticeDialog();
    WidgetsBinding.instance.addObserver(this);

    return GetBuilder<IndexController>(
      builder: (_) {
        controller.mContext = context1;
        return _content();
      },
    );
  }

  showNoticeDialog() async {
    var status = await Permission.notification.status;
    showTipDialog();
    if(status.isDenied || status.isPermanentlyDenied){
      showDialog(context: context, builder: (BuildContext context1) {
        return MySimpleDialog(callBack: (String content) {
          if(content == 'cancel'){
            Navigator.pop(context1);
          }else if(content == 'sure'){
            openAppSettings();
            Navigator.pop(context1);
          }
        },
          msg:'请在设置中打开通知',
          sureText: "允许通知",
        );
      });
    }else{
    }
  }

  showTipDialog(){
    if(UserUtil.getTip().isEmpty){
      UserUtil.saveTip("init");
      showDialog(context: context, builder: (BuildContext context1) {
        return TipDialog(callBack: (String content) {
          if(content == 'cancel'){
            Navigator.pop(context1);
          }else if(content == 'sure'){
            Navigator.pop(context1);
          }
        },
        );
      });
    }
  }


  //监听程序进入前后台的状态改变的方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("应用状态======"+state.toString());
    switch (state) {
    //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        print("应用进入前台======");
        controller.isFront = true;
        controller._getUnReadTotal();
        break;
    //应用状态处于闲置状态，并且没有用户的输入事件，
    // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
    // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        controller.isFront = false;
        controller._getUnReadTotal();
        print("应用处于不可见状态 后台======");
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

  Widget _item(image, text, selected) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        text == '我要卖'
            ? Container(
                width: 16.w,
                height: 16.h,
              )
            : Image.asset(
                image,
                width: 16.w,
                height: 16.h,
              ),
        SizedBox(
          height: 5.h,
        ),
        Text(
          text,
          style: TextStyle(
              color: selected || (text == '我要卖' && controller.page == 2)
                  ? Color(0xFF007BE5)
                  : Color(0xFF333333),
              fontSize: 12.sp),
        )
      ],
    );
  }

  Widget showDialogContainer(Function state, context1){
    return Stack(
        children: [
        Container(
        child:    Container(
          padding: EdgeInsets.all(22.w),
            height: Get.height - 86.h,
            width: Get.width,
           color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 38.h,),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('我要卖',style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF333333),
                        fontSize: 25.sp
                    ),),
                    SizedBox(height: 10.h,),
                    Row(
                      children: [
                        Image.asset(Constant.IMG_BASE+"sell1.png",width: 16.w,height: 17.h,),
                        SizedBox(width: 5.w,),
                        Text('专业代售平台，客服随时在线',style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: 15.sp
                        ),),
                      ],
                    ),
                  ],
                ),
                SizedBox(height: 33.h,),
                Container(
                    padding: EdgeInsets.all(10.w),
                    decoration: BoxDecoration(
                        color: const Color(0xFFF2F8FF),
                        borderRadius: BorderRadius.circular(7.r)
                    ),
                    child: InkWell(
                      onTap: (){
                        Navigator.pop(context1);
                        state(() {
                          Constant.tabFirst = true;
                        });
                      },
                    child:  Stack(
                      children: [
                        Container(
                          padding: EdgeInsets.all(18.w),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(7.r),
                            border: Border.all(width: 1.w, color: const Color(0xFF3F9BEB)),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Image.asset(Constant.IMG_BASE+"sell2.png",width: 21.w,height: 21.w,),
                                  SizedBox(width: 7.w,),
                                  Text('自行出售',style: TextStyle(
                                      color: Color(0xFF188FF6),
                                      fontSize: 15.sp
                                  ),),
                                ],
                              ),
                              Text('1.卖家自行发布商品信息到平台；',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 13.sp
                              ),),
                              Text('2.官方客服人员审核所发布商品；；',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 13.sp
                              ),),
                              Text('3.卖家下单，客服通知您上线交易；',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 13.sp
                              ),),
                              Text('4.交易成功，资金提现到您账户； ',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 13.sp
                              ),),
                            ],
                          ),

                        ),
                        Positioned(child: Image.asset(Constant.IMG_BASE+"sell3.png",width: 60.w,height: 47.h,),
                          right: 13.w,bottom: 13.h,
                        )
                      ],
                    )
                    )
                ),
                SizedBox(height: 24.h,),
                Container(
                    padding: EdgeInsets.all(10.w),
                    decoration: BoxDecoration(
                        color: const Color(0xFFFFFBE8),
                        borderRadius: BorderRadius.circular(7.r)
                    ),
                    child: InkWell(
                      onTap: (){
                        state(() {
                          Constant.tabFirst = false;
                        });

                        Navigator.pop(context1);
                      },
    child: Stack(
      children: [
        Container(
          padding: EdgeInsets.all(18.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(7.r),
            border: Border.all(width: 1.w, color: const Color(0xFFF28925)),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Image.asset(Constant.IMG_BASE+"sell4.png",width: 21.w,height: 21.w,),
                  SizedBox(width: 7.w,),
                  Text('快速回收',style: TextStyle(
                      color: Color(0xFFF28925),
                      fontSize: 15.sp
                  ),),
                ],
              ),
              Text('1.添加平台合作号商联系方式洽谈；',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 13.sp
              ),),
              Text('2.平台合作号商对商品评估报价；',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 13.sp
              ),),
              Text('3.您同意出售，协助合作号商换绑；',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 13.sp
              ),),
              Text('4.合作商户打款到您名下收款账户；',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 13.sp
              ),),
            ],
          ),
        ),
        Positioned(child: Image.asset(Constant.IMG_BASE+"sell5.png",width: 60.w,height: 47.h,),
          right: 13.w,bottom: 13.h,
        )
      ],
    )
    )
                ),

              ],
            )
        ))
        ]
    );
  }


  void changeUi(Function state) {
    state(() {
      controller.tabFirst = !controller.tabFirst;
    });
  }

  Widget _content() {
    //Stack里面包裹两个组件: Scaffold 和 FloatingActionButtonhome:
    return Stack(
      children: <Widget>[
        //Scaffold里面按照之前的写法body->PageView,bottomNavigationBar直接使用BottomNavigationBar
        Scaffold(
          body: PageView(
            physics: const NeverScrollableScrollPhysics(),
            controller: controller.pageController,
            onPageChanged: (e) {
              tabbarEventBus.fire(TabChangedEvent(e));
              if (e == 2) {
                Constant.clcikSellTab = true;
              } else {
                controller.preIndex = e;
                Constant.clcikSellTab = false;
              }
            },
            children: <Widget>[
              HomePage(),
              HotPage('buy'),
              HotPage('sell'),
              // Sell2Page(),
              MsgPage(),
              MyPage(),
            ],
          ),
          bottomNavigationBar: Container(
              child: BottomNavigationBar(
            backgroundColor: Colors.white,
            elevation: 10,
            type: BottomNavigationBarType.fixed,
            selectedFontSize: 0,
            unselectedFontSize: 0,
            showSelectedLabels: false,
            showUnselectedLabels: false,
            selectedLabelStyle:
                TextStyle(color: Color(0xFFF43F50), fontSize: 12.sp),
            unselectedLabelStyle:
                TextStyle(color: Color(0xFF333333), fontSize: 12.sp),
            items: [
              BottomNavigationBarItem(
                  icon: _item('assets/images/icon_home.png', '首页', false),
                  label: '首页',
                  activeIcon:
                      _item('assets/images/icon_home_y.png', '首页', true)),
              BottomNavigationBarItem(
                  icon: _item('assets/images/icon_buy.png', '我要买', false),
                  label: '我要买',
                  activeIcon:
                      _item('assets/images/icon_buy_y.png', '我要买', true)),
              BottomNavigationBarItem(
                  icon: _item('assets/images/icon_sell.png', '我要卖', false),
                  label: '我要卖',
                  activeIcon:
                      _item('assets/images/icon_sell.png', '我要卖', false)),
              BottomNavigationBarItem(
                icon: controller.unReadNum > 0
                    ? badges.Badge(
                        badgeContent: Text(
                          controller.unReadNum.toString(),
                          style:
                              TextStyle(color: Colors.white, fontSize: 12.sp),
                        ),
                        child: _item('assets/images/icon_msg.png', '消息', false),
                      )
                    : _item('assets/images/icon_msg.png', '消息', false),
                label: '消息',
                activeIcon: controller.unReadNum > 0
                    ? badges.Badge(
                        badgeContent: Text(
                          controller.unReadNum.toString(),
                          style:
                              TextStyle(color: Colors.white, fontSize: 12.sp),
                        ),
                        child:
                            _item('assets/images/icon_msg_y.png', '消息', false),
                      )
                    : _item('assets/images/icon_msg_y.png', '消息', true),

                // activeIcon:_item('assets/images/icon_msg_y.png','消息',true)
              ),

              // BottomNavigationBarItem(
              //     icon: _item('assets/images/icon_msg.png','消息',false),
              //     label: '消息',
              //     activeIcon:_item('assets/images/icon_msg_y.png','消息',true)
              // ),
              BottomNavigationBarItem(
                  icon: _item('assets/images/icon_me.png', '我的', false),
                  label: '我的',
                  activeIcon: _item('assets/images/icon_me_y.png', '我的', true)),
            ],
            onTap: (e) {
              print('onTap$e');
              if ((e == 3) && !Common.checkLoginOrReal(context)) {
              } else if (e == 4 && !Common.checkLogin()) {
                Get.to(() => LoginCodePage(), preventDuplicates: false);
              } else {
                controller.page = e;
                controller.pageController.animateToPage(controller.page,
                    duration: Duration(milliseconds: 50),
                    curve: Curves.fastOutSlowIn);
                tabbarEventBus.fire(TabChangedEvent(e));
                controller.update();
              }
            },
            currentIndex: controller.page,
          )),
        ),
        //在整个界面的上层放一个FloatingActionButton 组件,位置在底部居中
        Align(
          alignment: Alignment.bottomCenter,
          child: Padding(
            padding: EdgeInsets.only(bottom: 36.h),
            child: FloatingActionButton(
              backgroundColor: Colors.white,
              elevation: 0,
              child: Image.asset(
                'assets/images/icon_sell.png',
                width: 40.w,
                height: 40.h,
              ),
              onPressed: () {
                if (Common.checkLoginOrReal(context)) {
                  controller.tabFirst = true;
                  showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (context1) {
                        return StatefulBuilder(
                          builder: (context, state) {
                            return Container(
                              child: Material(
                                color: Colors.transparent,
                                child: showDialogContainer(state, context1),
                              ),
                            );
                          },
                        );
                      });

                  controller.page = 2;
                  controller.pageController.animateToPage(controller.page,
                      duration: Duration(milliseconds: 50),
                      curve: Curves.fastOutSlowIn);
                  controller.update();
                }
              },
            ),
          ),
        ),
      ],
    );
  }
}
